//
//  NSString+GXDES.m
//  24-加密
//
//  Created by Snow on 16/8/16.
//  Copyright © 2016年 Snow. All rights reserved.
//

#import "NSString+GXDES.h"
#import <CommonCrypto/CommonCrypto.h>
//必须8位
#define key @"01234567"
static Byte iv[] = {1, 2, 3, 4, 5, 6, 7, 8};
@implementation NSString (GXDES)
//字符串对称加密(DES)
- (NSString *)stringWithDES
{
    //1.将字符串本身转换成C字符串
    const char *string = [self UTF8String];
    //接受容器
    size_t dataOutMoves = 0;
    ////容器大小
    unsigned char byte[1024];
    //加密过程
    //参数1:加密/解密
    //参数2:加密/解密的方式 DES 3DES aes
    //参数3:分组密码的选项
    //参数4:秘钥
    //参数5:key(秘钥)的大小
    //参数6:向量
    //参数7:c的字符串
    //参数8:字符串的length
    //参数9:接收容器
    //参数10:容器大小
    //参数11:容器最终的个数
     CCCryptorStatus sryptorStatus =  CCCrypt(kCCEncrypt, kCCAlgorithmDES,  kCCOptionPKCS7Padding , [key UTF8String], kCCKeySizeDES, iv, string, strlen(string), byte, 1024, &dataOutMoves);
    //判断成功
    if (sryptorStatus == kCCSuccess) {
        NSLog(@"succes");
        //转成字符串---base64返回
        NSData *desData = [NSData dataWithBytes:byte length:dataOutMoves];
        NSString *desbase64String = [desData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
        return desbase64String;
    } else {
        //失败返回空
        NSLog(@"failed");
        return nil;
    }
}
//字符串对称解密(DES)
- (NSString *)desWithString
{
    NSData *data = [[NSData alloc] initWithBase64EncodedString:self options:NSDataBase64DecodingIgnoreUnknownCharacters];
    const void *byte = data.bytes;
    unsigned char buffer[1024];
    size_t dataOutMoves = 0;
//    const char *string = [self UTF8String];
    CCCryptorStatus sryptorStatus =  CCCrypt(kCCDecrypt, kCCAlgorithmDES,  kCCOptionPKCS7Padding , [key UTF8String], kCCKeySizeDES, iv, byte, [data length], buffer, 1024, &dataOutMoves);
    if (sryptorStatus == kCCSuccess) {
        NSData *sourceData = [[NSData alloc] initWithBytes:buffer length:dataOutMoves];
        NSString *sourceString = [[NSString alloc] initWithData:sourceData encoding:NSUTF8StringEncoding];
        NSLog(@"succes");
        return sourceString;
    } else {
        NSLog(@"failed");
    return nil;
    }
}

@end
